import { ref } from 'vue';

export function FakeDoubleCodeGeneration() {
  const generatedCode = ref('');
    
  const generateTypeDefinition = (tableConfig) => {
    const { tableName, data } = tableConfig;
    
    const fieldsDefinition = data.map((field, index) => {
      const [table, fieldName] = field.referenceTableField?.split('.') || [];
      const isLastField = index === data.length - 1;
      const comma = isLastField ? '' : ',';
      return `       ${field.field.padEnd(20)} LIKE ${table}.${fieldName || field.field}${comma}`.padEnd(65) + `#${field.description}`;
    }).join('\n');

    return `TYPE   ${tableName}      RECORD     \n${fieldsDefinition}\n      END RECORD`;
  };

  //表格中的主键字段
  const primaryKeyFields = (tableConfig) => {
    return tableConfig.data
      .filter(field => field.keyword === 'Y')
      .map(field => field.field);
  };

  const programName = (formData) => {
    return `${formData.programId.slice(3)}`;
  };

  const generateFakeDoubleCode = (formData, tables) => {
    // 获取主表和子表
    const masterTable = tables[0];  // 主表永远是第一个
    const detailTables = tables.slice(1);  // 其余的都是子表

    if (!masterTable) {
      console.error('需要主表配置');
      return '';
    }

    // 获取主表和子表的主键字段
    const masterPkFields = primaryKeyFields(masterTable);
    const masterWhereClause = masterPkFields.map(field => `${field}=?`).join(' AND ');

    // 程序中命名
    const programNameId = programName(formData);

    // 生成所有表的类型定义
    const masterTypeDefinition = generateTypeDefinition(masterTable);
    const detailTypeDefinitions = detailTables.map(table => generateTypeDefinition(table));

    let code = `
# 程序名称: ${formData.programId}
# 作   者: ${formData.author}
# 创建时间: ${new Date().toLocaleString()}

DATABASE ds
GLOBALS "../../../tiptop/config/top.global"

#主表类型定义
${masterTypeDefinition}

#子表类型定义
${detailTypeDefinitions.join('\n\n')}

#主表全局变量定义
DEFINE ${masterTable.arrayName}   ${masterTable.tableName}      
DEFINE ${masterTable.arrayName}_t ${masterTable.tableName}      

#子表全局变量定义
${detailTables.map(table => `
DEFINE ${table.arrayName}   DYNAMIC ARRAY OF ${table.tableName}      #子表全局
DEFINE ${table.arrayName}_t ${table.tableName}                       #子表旧值
`).join('\n')}

#表主键字段
DEFINE ${masterTable.arrayName}_key LIKE type_file.chr100

#其他全局变量
DEFINE   	g_wc,g_wc2,g_sql     STRING
DEFINE   	g_rec_b         LIKE type_file.num5             
DEFINE   	l_ac            LIKE type_file.num5               
DEFINE   	l_cmd           LIKE type_file.chr1000       
DEFINE 		g_forupd_sql  STRING     
DEFINE 		g_before_input_done  LIKE type_file.num5          
DEFINE 		p_row,p_col     LIKE type_file.num5          
DEFINE   	g_cnt           LIKE type_file.num10           
DEFINE   	g_i             LIKE type_file.num5     
DEFINE   	g_msg           LIKE type_file.chr1000      
DEFINE   	g_bookno        LIKE aaa_file.aaa01   
DEFINE   	g_curs_index    LIKE type_file.num10        
DEFINE   	g_row_count     LIKE type_file.num10         
DEFINE   	g_jump          LIKE type_file.num10         
DEFINE   	mi_no_ask       LIKE type_file.num5 
DEFINE      g_statebar      STRING

################################################################################
# Descriptions...: 主函数入口
# Memo...........:
# Usage..........: CALL ${formData.programId}()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
MAIN
DEFINE p_row,p_col         LIKE type_file.num5

       OPTIONS                                          
       INPUT NO WRAP                                                 
       DEFER INTERRUPT                                                

       IF (NOT cl_user()) THEN                                       
          EXIT PROGRAM                                                
       END IF

       WHENEVER ERROR CALL cl_err_msg_log                             
       IF (NOT cl_setup("${formData.module}")) THEN                                 
          EXIT PROGRAM                                                
       END IF

       CALL cl_used(g_prog,g_time,1) RETURNING g_time                 

       LET g_forupd_sql = " SELECT * FROM ${masterTable.insertTable} WHERE ${masterWhereClause} FOR UPDATE  "
       LET g_forupd_sql = cl_forupd_sql(g_forupd_sql)
       DECLARE ${programNameId}_cl CURSOR FROM g_forupd_sql                       

       LET g_statebar = "Total: %1 / %2"                              

       LET p_row = 2 
       LET p_col = 2

       OPEN WINDOW ${programNameId}_w AT p_row,p_col WITH FORM "${formData.programPath}"
            ATTRIBUTE (STYLE = g_win_style CLIPPED)                 

       CALL cl_ui_init()                                              

       LET g_action_choice = ""                                       
       CALL ${programNameId}_menu()                                               

       CLOSE WINDOW ${programNameId}_w                                            

       CALL cl_used(g_prog,g_time,2) RETURNING g_time                 

END MAIN

################################################################################
# Descriptions...: 主函数入口
# Memo...........:
# Usage..........: CALL ${programNameId}_menu()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_menu()
DEFINE l_cmd               STRING

       WHILE TRUE
            CALL ${programNameId}_bp("G")
            CASE g_action_choice

               WHEN "insert" 
                  IF cl_chk_act_auth() THEN 
                     CALL ${programNameId}_a()
                  END IF

               WHEN "query" 
                  IF cl_chk_act_auth() THEN
                     CALL ${programNameId}_q()
                  END IF

               WHEN "delete" 
                  IF cl_chk_act_auth() THEN
                     CALL ${programNameId}_r()
                  END IF
               
               WHEN "detail"
                  IF cl_chk_act_auth() THEN                      
                     CALL ${programNameId}_b()                   
                  ELSE
                     LET g_action_choice = NULL
                  END IF

               WHEN "output"
               {
                  IF cl_chk_act_auth() THEN                     
                     CALL ${programNameId}_out()               
                  END IF
               }

               WHEN "help"
                  CALL cl_show_help()                            

               WHEN "exit"
                  EXIT WHILE                                    

               WHEN "confirm" 
               {
                  IF cl_chk_act_auth() THEN
                     CALL ${programNameId}_confirm()
                  END IF
               }  

               WHEN "controlg"
                  CALL cl_cmdask()                              

               WHEN "locale"
                  CALL cl_dynamic_locale()                      
                  CALL cl_show_fld_cont()                       

               WHEN "about"
                  CALL cl_about()                                

               WHEN "related_document"
                  IF cl_chk_act_auth() THEN
                     CALL cl_doc()                            
                  END IF

               WHEN "exporttoexcel"
                  IF cl_chk_act_auth() THEN
                     CALL cl_export_to_excel(ui.Interface.getRootNode(),base.TypeInfo.create(${masterTable.arrayName}),'','')
                  END IF

             END CASE
       END WHILE

END FUNCTION

################################################################################
# Descriptions...: 查询条件
# Memo...........:
# Usage..........: CALL ${programNameId}_cs()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_cs()
DEFINE  lc_qbe_sn       LIKE gbm_file.gbm01    
 
    CLEAR FORM                             
    CALL ${detailTables[0].arrayName}.clear()
    CALL cl_set_head_visible("","YES")       
   
   INITIALIZE ${masterTable.arrayName}.* TO NULL    
    CONSTRUCT BY NAME g_wc ON ${masterTable.data.map(field => `${field.field}`).join(',')}
               BEFORE CONSTRUCT
                  CALL cl_qbe_init()

       ON ACTION controlp
         {
         CASE
            WHEN INFIELD(tc_abj01) 
                  CALL cl_init_qry_var()
                  LET g_qryparam.form ="q_pja2"
                  LET g_qryparam.default1 = g_tc_abj_a.tc_abj01
                  CALL cl_create_qry() RETURNING g_tc_abj_a.tc_abj01
                  SELECT pja02 INTO g_tc_abj_a.tc_abj02 FROM pja_file WHERE pja01=g_tc_abj_a.tc_abj01
                  DISPLAY BY NAME g_tc_abj_a.tc_abj01,g_tc_abj_a.tc_abj02
                  NEXT FIELD tc_abj01
            OTHERWISE EXIT CASE
         END CASE
         }

      ON IDLE g_idle_seconds
          CALL cl_on_idle()
          CONTINUE CONSTRUCT
 
      ON ACTION about         
         CALL cl_about()      
 
      ON ACTION help         
         CALL cl_show_help()  
 
      ON ACTION controlg     
         CALL cl_cmdask()     

      ON ACTION qbe_select
		   CALL cl_qbe_list() RETURNING lc_qbe_sn
		   CALL cl_qbe_display_condition(lc_qbe_sn)

    END CONSTRUCT

    LET g_wc = g_wc CLIPPED,cl_get_extra_cond(null, null) 
    IF INT_FLAG THEN RETURN END IF
 
    CONSTRUCT g_wc2 ON ${detailTables[0].data.map(field => `${field.field}`).join(',')}            
         FROM ${detailTables[0].data.map(field => `${formData.formName}[1].${field.field}`).join(',')}

		BEFORE CONSTRUCT
		   CALL cl_qbe_display_condition(lc_qbe_sn)

       ON ACTION controlp
         #CASE
         #   WHEN INFIELD(tc_abj03) 
         #         CALL cl_init_qry_var()
         #         LET g_qryparam.state = 'c'
         #         LET g_qryparam.form ="cq_ima"
         #         CALL cl_create_qry() RETURNING g_qryparam.multiret
         #         DISPLAY g_qryparam.multiret TO tc_abj03
         #         NEXT FIELD tc_abj03
         #   OTHERWISE EXIT CASE
         #END CASE

      ON IDLE g_idle_seconds
          CALL cl_on_idle()
          CONTINUE CONSTRUCT
 
      ON ACTION about         
         CALL cl_about()      
 
      ON ACTION help          
         CALL cl_show_help()  
   
      ON ACTION controlg     
         CALL cl_cmdask()     
 
      ON ACTION qbe_save
         CALL cl_qbe_save()

    END CONSTRUCT

    IF INT_FLAG THEN LET INT_FLAG=0 RETURN END IF

    IF cl_null(g_wc2) THEN LET g_wc2 = " 1=1" END IF 
 
    IF g_wc2 = " 1=1 " THEN
       LET g_sql = "SELECT distinct ${masterTable.data.map(field => field.field).join(',')} FROM ${masterTable.insertTable} ", 
                   " WHERE ", g_wc CLIPPED,
                   "  "
    ELSE
       LET g_sql = "SELECT distinct ${masterTable.data.map(field => field.field).join(',')} ",
                   "  FROM ${masterTable.insertTable} ",
                   "  WHERE ", g_wc CLIPPED, " AND ",g_wc2 CLIPPED,
                   "  "
    END IF
 
    PREPARE ${programNameId}_prepare FROM g_sql
    DECLARE ${programNameId}_cs                        
        SCROLL CURSOR WITH HOLD FOR ${programNameId}_prepare
 
    IF g_wc2 = " 1=1" THEN
        LET g_sql = "  SELECT COUNT(1) from (",
                    "  SELECT distinct ${masterTable.data.map(field => field.field).join(',')} FROM ${masterTable.insertTable}  WHERE ",g_wc CLIPPED, " ",
                    "  ) "
    ELSE
        LET g_sql = "  SELECT COUNT(1) from (",
                    "  SELECT distinct ${masterTable.data.map(field => field.field).join(',')} FROM ${masterTable.insertTable}  WHERE ",g_wc CLIPPED," AND ",g_wc2 CLIPPED," ",
                    "  ) "
    END IF

    PREPARE ${programNameId}_precount FROM g_sql
    DECLARE ${programNameId}_count CURSOR FOR ${programNameId}_precount
 
END FUNCTION


################################################################################
# Descriptions...: 输入函数
# Memo...........:
# Usage..........: CALL ${programNameId}_a()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_a()
    
    IF s_shut(0) THEN RETURN END IF
    
    MESSAGE ""
    CLEAR FORM
    CALL ${detailTables[0].arrayName}.clear()
 
    INITIALIZE ${masterTable.arrayName}.* TO NULL

    #LET ${masterTable.arrayName}_t = NULL
    LET ${masterTable.arrayName}_t.* = ${masterTable.arrayName}.*

   #主表的默认值
   ${masterTable.data.map(field => {
     if (field.defaultValue) {
       return `    LET ${masterTable.arrayName}.${field.field} = "${field.defaultValue}"`;
     }
     return '';
   }).filter(line => line).join('\n')}

    CALL cl_opmsg('a')
    WHILE TRUE
        CALL ${programNameId}_i("a")      

        IF INT_FLAG THEN                  
            INITIALIZE ${masterTable.arrayName}.* TO NULL
            LET INT_FLAG = 0
            CALL cl_err('',9001,0)
            EXIT WHILE
        END IF

        IF ${masterTable.arrayName}.${masterPkFields[0]} IS NULL THEN    
           CONTINUE WHILE
        END IF
 
        LET ${masterTable.arrayName}_key = ${masterTable.arrayName}.${masterPkFields[0]}        
        LET ${masterTable.arrayName}_t.* = ${masterTable.arrayName}.*
 
        CALL ${detailTables[0].arrayName}.clear()    
        LET g_rec_b = 0 
 
        CALL ${programNameId}_b()                      

        EXIT WHILE
    END WHILE
END FUNCTION

################################################################################
# Descriptions...: 输入函数
# Memo...........:
# Usage..........: CALL ${programNameId}_i(p_cmd)
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_i(p_cmd)
DEFINE l_flag          LIKE type_file.chr1            
DEFINE l_n1            LIKE type_file.num5         
DEFINE p_cmd           LIKE type_file.chr1                 


    DISPLAY BY NAME ${masterTable.data.map(field => `${masterTable.arrayName}.${field.field}`).join(',')}
    CALL cl_set_head_visible("","YES")       

    INPUT BY NAME
        ${masterTable.data.map(field => `${masterTable.arrayName}.${field.field}`).join(',')} WITHOUT DEFAULTS
 
        BEFORE INPUT
           LET g_before_input_done = FALSE
          # CALL i002_set_entry(p_cmd)
          # CALL i002_set_no_entry(p_cmd)
           LET g_before_input_done = TRUE
        
        ${masterTable.data.map(field => `
        AFTER FIELD ${field.field}
            IF cl_null(${masterTable.arrayName}.${field.field}) THEN
               LET ${masterTable.arrayName}.${field.field} = ${field.defaultValue ? `"${field.defaultValue}"` : 'NULL'}
            END IF
        `).join('\n')}

        ON ACTION CONTROLF                  
         CALL cl_set_focus_form(ui.Interface.getRootNode()) RETURNING g_fld_name,g_frm_name 
         CALL cl_fldhelp(g_frm_name,g_fld_name,g_lang) 
          
        ON ACTION controlp
         {CASE
            WHEN INFIELD(${masterTable.arrayName}.${masterPkFields[0]}) 
                  CALL cl_init_qry_var()
                  LET g_qryparam.form ="q_pja2"
                  LET g_qryparam.default1 = ${masterTable.arrayName}.${masterPkFields[0]}
                  CALL cl_create_qry() RETURNING ${masterTable.arrayName}.${masterPkFields[0]}
                  DISPLAY BY NAME ${masterTable.arrayName}.${masterPkFields[0]}
                  NEXT FIELD ${masterTable.arrayName}.${masterPkFields[0]}
            OTHERWISE EXIT CASE
         END CASE}

        ON ACTION CONTROLR
           CALL cl_show_req_fields()
 
        ON ACTION CONTROLG
           CALL cl_cmdask()
 
        ON IDLE g_idle_seconds
            CALL cl_on_idle()
            CONTINUE INPUT
 
        ON ACTION about         
            CALL cl_about()      

        ON ACTION help         
           CALL cl_show_help()  

    END INPUT
END FUNCTION

################################################################################
# Descriptions...: 查询函数
# Memo...........:
# Usage..........: CALL ${programNameId}_q()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_q()
 
    LET g_row_count = 0
    LET g_curs_index = 0
    CALL cl_navigator_setting( g_curs_index, g_row_count )
    INITIALIZE ${masterTable.arrayName}.* TO NULL             
 
    CALL cl_opmsg('q')
    MESSAGE ""
    DISPLAY '   ' TO FORMONLY.cnt 

    CALL ${programNameId}_cs()
    IF INT_FLAG THEN
        LET INT_FLAG = 0
        INITIALIZE ${masterTable.arrayName}.* TO NULL
        RETURN
    END IF
 
    MESSAGE " SEARCHING ! " 
 
    OPEN ${programNameId}_cs                          
    IF SQLCA.sqlcode THEN
       CALL cl_err('',SQLCA.sqlcode,0)
       INITIALIZE ${masterTable.arrayName}.* TO NULL
    ELSE
       OPEN ${programNameId}_count
       FETCH ${programNameId}_count INTO g_row_count
       DISPLAY g_row_count TO FORMONLY.cnt 
       CALL ${programNameId}_fetch('F')         
    END IF
 
    MESSAGE ""
 
END FUNCTION

################################################################################
# Descriptions...: 资料获取
# Memo...........:
# Usage..........: CALL ${programNameId}_fetch()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_fetch(p_flag)
DEFINE  p_flag          LIKE type_file.chr1                 

    CASE p_flag
        WHEN 'N' FETCH NEXT     ${programNameId}_cs INTO ${masterTable.data
            .filter(field => field.keyword === 'Y')
            .map(field => `${masterTable.arrayName}.${field.field}`)
            .join(',')}
        WHEN 'P' FETCH PREVIOUS ${programNameId}_cs INTO ${masterTable.data
            .filter(field => field.keyword === 'Y')
            .map(field => `${masterTable.arrayName}.${field.field}`)
            .join(',')}
        WHEN 'F' FETCH FIRST    ${programNameId}_cs INTO ${masterTable.data
            .filter(field => field.keyword === 'Y')
            .map(field => `${masterTable.arrayName}.${field.field}`)
            .join(',')}
        WHEN 'L' FETCH LAST     ${programNameId}_cs INTO ${masterTable.data
            .filter(field => field.keyword === 'Y')
            .map(field => `${masterTable.arrayName}.${field.field}`)
            .join(',')}
        WHEN '/'
            IF (NOT mi_no_ask) THEN
                CALL cl_getmsg('fetch',g_lang) RETURNING g_msg
                LET INT_FLAG = 0  
                PROMPT g_msg CLIPPED || ': ' FOR g_jump  
                    ON IDLE g_idle_seconds
                       CALL cl_on_idle()
 
      ON ACTION about         
         CALL cl_about()      
 
      ON ACTION help         
         CALL cl_show_help() 
 
      ON ACTION controlg      
         CALL cl_cmdask()     
                END PROMPT
                IF INT_FLAG THEN
                    LET INT_FLAG = 0
                    EXIT CASE
                END IF
            END IF
            FETCH ABSOLUTE g_jump ${programNameId}_cs INTO ${masterTable.data
            .filter(field => field.keyword === 'Y')
            .map(field => `${masterTable.arrayName}.${field.field}`)
            .join(',')}

            LET mi_no_ask = FALSE
    END CASE
 
    IF SQLCA.sqlcode THEN
        CALL cl_err(${masterTable.arrayName}.${masterPkFields[0]},SQLCA.sqlcode,0)
        INITIALIZE ${masterTable.arrayName}.* TO NULL  
        LET ${masterTable.arrayName}.${masterPkFields[0]} = NULL      
        RETURN
    ELSE
       CASE p_flag
          WHEN 'F' LET g_curs_index = 1
          WHEN 'P' LET g_curs_index = g_curs_index - 1
          WHEN 'N' LET g_curs_index = g_curs_index + 1
          WHEN 'L' LET g_curs_index = g_row_count
          WHEN '/' LET g_curs_index = g_jump          
       END CASE
    
       CALL cl_navigator_setting( g_curs_index, g_row_count )
    END IF
    CALL ${programNameId}_show()

END FUNCTION

################################################################################
# Descriptions...: 资料显示
# Memo...........:
# Usage..........: CALL ${programNameId}_show()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_show()
    LET ${masterTable.arrayName}_t.* = ${masterTable.arrayName}.*               
    DISPLAY BY NAME ${masterTable.data.map(field => `${masterTable.arrayName}.${field.field}`).join(',')}

    CALL ${programNameId}_b_fill(g_wc2)                 
    CALL cl_show_fld_cont()                   
END FUNCTION

################################################################################
# Descriptions...: 单身数据维护
# Memo...........:
# Usage..........: CALL ${programNameId}_b()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_b()
DEFINE    l_sql,l_sql1    VARCHAR(500)
DEFINE    l_ac_t,l_n1     LIKE type_file.num5               
DEFINE    l_n,l_ac1,l_ac2 LIKE type_file.num5               
DEFINE    l_lock_sw       LIKE type_file.chr1               
DEFINE    p_cmd           LIKE type_file.chr1               
DEFINE    l_allow_insert  LIKE type_file.num5               
DEFINE    l_allow_delete  LIKE type_file.num5                
    
    LET g_action_choice = ""
 
    IF ${masterTable.arrayName}.${masterPkFields[0]} IS NULL THEN RETURN END IF
 
    CALL cl_opmsg('b')
 
    LET g_forupd_sql = " SELECT ${detailTables[0].data.map(field => `${field.field}`).join(',')} ",
                       "   FROM ${detailTables[0].insertTable}  ",
                       "  WHERE ${masterPkFields.map(field => `${field} = ?`).join(' AND ')} ",
                       "    AND ${detailTables[0].data
                           .filter(field => field.keyword === 'Y')
                           .map(field => `${field.field} = ?`)
                           .join(' AND ')} ",
                       "    FOR UPDATE "
    LET g_forupd_sql = cl_forupd_sql(g_forupd_sql)
    DECLARE ${programNameId}_bcl CURSOR FROM g_forupd_sql
 
    LET l_ac_t = 0
    LET l_allow_insert = cl_detail_input_auth("insert")
    LET l_allow_delete = cl_detail_input_auth("delete")

    INPUT ARRAY ${detailTables[0].arrayName} WITHOUT DEFAULTS FROM ${formData.formName}.* 
          ATTRIBUTE(COUNT=g_rec_b,MAXCOUNT=g_max_rec,UNBUFFERED,
                    INSERT ROW=l_allow_insert,DELETE ROW=l_allow_delete,APPEND ROW=l_allow_insert)   

           BEFORE INPUT
            IF g_rec_b != 0 THEN
               CALL fgl_set_arr_curr(l_ac)
            END IF

            BEFORE ROW
            LET p_cmd = ''
            LET l_ac = ARR_CURR()
            LET l_lock_sw = 'N'            
            LET l_n  = ARR_COUNT()

            BEGIN WORK
            IF g_rec_b >= l_ac THEN
               LET p_cmd='u'
               LET ${detailTables[0].arrayName}_t.* = ${detailTables[0].arrayName}[l_ac].*
               OPEN ${programNameId}_bcl USING ${masterPkFields
                   .map(field => `${masterTable.arrayName}.${field}`)
                   .concat(detailTables[0].data
                       .filter(field => field.keyword === 'Y')
                       .map(field => `${detailTables[0].arrayName}[l_ac].${field.field}`))
                   .join(',')}
               IF SQLCA.sqlcode THEN
                  CALL cl_err(${detailTables[0].arrayName}_t.${detailTables[0].data[0].field},SQLCA.sqlcode,1)
                  LET l_lock_sw = "Y"
               ELSE 
                  FETCH ${programNameId}_bcl INTO ${detailTables[0].data
                      .map(field => `${detailTables[0].arrayName}[l_ac].${field.field}`)
                      .join(',')}
                  IF SQLCA.sqlcode THEN
                     CALL cl_err(${detailTables[0].arrayName}_t.${detailTables[0].data[0].field},SQLCA.sqlcode,1)
                     LET l_lock_sw = "Y"
                  END IF 
               END IF
               CALL cl_show_fld_cont()  
               LET g_before_input_done = FALSE
            END IF

        BEFORE INSERT
            LET l_n = ARR_COUNT()
            LET p_cmd='a'
            INITIALIZE ${detailTables[0].arrayName}[l_ac].* TO NULL  
            LET ${detailTables[0].arrayName}_t.* = ${detailTables[0].arrayName}[l_ac].*         
            CALL cl_show_fld_cont()    
            LET g_before_input_done = FALSE
           # CALL ${programNameId}_set_entry(p_cmd)
           # CALL ${programNameId}_set_no_entry(p_cmd)
            LET g_before_input_done = TRUE            

        ${detailTables[0].data.map(field => `
        AFTER FIELD ${field.field}
            IF cl_null(${detailTables[0].arrayName}[l_ac].${field.field}) THEN
               LET ${detailTables[0].arrayName}[l_ac].${field.field} = ${field.defaultValue ? `"${field.defaultValue}"` : 'NULL'}
            END IF
        `).join('\n')}

        AFTER INSERT
            IF INT_FLAG THEN
               CALL cl_err('',9001,0)
               LET INT_FLAG = 0
               CANCEL INSERT
            END IF

            INSERT INTO ${detailTables[0].insertTable}(${masterPkFields
                .concat(detailTables[0].data.map(field => field.field))
                .join(',')})
                          VALUES(${masterPkFields
                              .map(field => `${masterTable.arrayName}.${field}`)
                              .concat(detailTables[0].data
                                  .map(field => `${detailTables[0].arrayName}[l_ac].${field.field}`))
                              .join(',')})
            IF SQLCA.sqlcode THEN
               CALL cl_err3("ins","${detailTables[0].insertTable}",${detailTables[0].arrayName}[l_ac].${detailTables[0].data[0].field},"",SQLCA.sqlcode,"","",1)
               CANCEL INSERT
            ELSE
               COMMIT WORK
               LET g_rec_b = g_rec_b + 1
               MESSAGE 'INSERT O.K'
            END IF

        BEFORE DELETE                                           
            IF l_lock_sw = "Y" THEN 
               CALL cl_err("", -263, 1) 
               CANCEL DELETE 
            END IF 
               
            DELETE FROM ${detailTables[0].insertTable}    
                WHERE ${masterPkFields
                    .map(field => `${field} = ${masterTable.arrayName}.${field}`)
                    .concat(detailTables[0].data
                        .filter(field => field.keyword === 'Y')
                        .map(field => `${field.field} = ${detailTables[0].arrayName}_t.${field.field}`))
                    .join('\n                  AND ')}
            IF SQLCA.SQLERRD[3] = 0 THEN
               CALL cl_err3("del","${detailTables[0].insertTable}",${detailTables[0].arrayName}_t.${detailTables[0].data[0].field},"",SQLCA.sqlcode,"","",1)
               ROLLBACK WORK
               CANCEL DELETE 
            END IF

            LET g_rec_b=g_rec_b-1
            DISPLAY g_rec_b TO FORMONLY.cn2
            COMMIT WORK

        ON ROW CHANGE
            IF INT_FLAG THEN
               CALL cl_err('',9001,0)
               LET INT_FLAG = 0
               LET ${detailTables[0].arrayName}[l_ac].* = ${detailTables[0].arrayName}_t.*
               CLOSE ${programNameId}_bcl
               ROLLBACK WORK
               EXIT INPUT
            END IF

            IF l_lock_sw = 'Y' THEN
               CALL cl_err(${detailTables[0].arrayName}[l_ac].${detailTables[0].data[0].field},-263,1)
               LET ${detailTables[0].arrayName}[l_ac].* = ${detailTables[0].arrayName}_t.*
            ELSE
               UPDATE ${detailTables[0].insertTable} 
                  SET ${detailTables[0].data.map(field => 
                      `${field.field}=${detailTables[0].arrayName}[l_ac].${field.field}`).join(',\n                      ')}
                WHERE ${masterPkFields
                    .map(field => `${field} = ${masterTable.arrayName}.${field}`)
                    .concat(detailTables[0].data
                        .filter(field => field.keyword === 'Y')
                        .map(field => `${field.field} = ${detailTables[0].arrayName}_t.${field.field}`))
                    .join('\n                  AND ')}

               IF SQLCA.sqlcode THEN
                  CALL cl_err3("upd","${detailTables[0].insertTable}",${detailTables[0].arrayName}[l_ac].${detailTables[0].data[0].field},"",SQLCA.sqlcode,"","",1)
                  LET ${detailTables[0].arrayName}[l_ac].* = ${detailTables[0].arrayName}_t.*
               ELSE
                  MESSAGE 'UPDATE O.K'
                  COMMIT WORK
               END IF
            END IF

        AFTER ROW
            DISPLAY g_rec_b TO FORMONLY.cnt
            LET l_ac = ARR_CURR()
            IF INT_FLAG THEN
               CALL cl_err('',9001,0)
               LET INT_FLAG = 0
               IF p_cmd = 'u' THEN
                  LET ${detailTables[0].arrayName}[l_ac].* = ${detailTables[0].arrayName}_t.*
               ELSE
                  CALL ${detailTables[0].arrayName}.deleteElement(l_ac)
                  IF g_rec_b != 0 THEN
                     LET g_action_choice = "query"
                     LET l_ac = l_ac_t
                  END IF
               END IF
               CLOSE ${programNameId}_bcl
               ROLLBACK WORK
               EXIT INPUT
            END IF
            LET l_ac_t = l_ac  
            CLOSE ${programNameId}_bcl
            COMMIT WORK

        ON ACTION controlp
           CALL cl_show_fld_cont()

        ON ACTION controls                                  
           CALL cl_set_head_visible("","AUTO")  

        ON ACTION controlg 
           CALL cl_cmdask()

        ON ACTION controlf                    
           CALL cl_set_focus_form(ui.Interface.getRootNode()) RETURNING g_fld_name,g_frm_name 
           CALL cl_fldhelp(g_frm_name,g_fld_name,g_lang) 

        ON IDLE g_idle_seconds
           CALL cl_on_idle()
           CONTINUE INPUT

        ON ACTION about         
           CALL cl_about()      
           CONTINUE INPUT

        ON ACTION help          
           CALL cl_show_help()  
           CONTINUE INPUT

      END INPUT
 
    CLOSE ${programNameId}_bcl
    COMMIT WORK
    CALL ${programNameId}_show()
END FUNCTION

################################################################################
# Descriptions...: 单身数据维护填充
# Memo...........:
# Usage..........: CALL ${programNameId}_b_fill(p_wc2)
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_b_fill(p_wc2) 
DEFINE   p_wc2           LIKE type_file.chr1000       
 
    LET g_sql = "SELECT ${detailTables[0].data.map(field => field.field).join(',')} ",
        "          FROM ${detailTables[0].insertTable} ",
        "         WHERE ${masterPkFields.map(field => 
            `${field} = '",${masterTable.arrayName}.${field},"'`).join(' AND ')}",
        "           AND ",p_wc2 CLIPPED,              
        "         ORDER BY 1 "        

    DISPLAY ' ################## : ',g_sql
    PREPARE ${programNameId}_pb FROM g_sql
    DECLARE ${detailTables[0].arrayName}_curs CURSOR FOR ${programNameId}_pb

    CALL ${detailTables[0].arrayName}.clear()

    LET g_cnt = 1
    MESSAGE "Searching!"
    FOREACH ${detailTables[0].arrayName}_curs INTO ${detailTables[0].arrayName}[g_cnt].*
        IF STATUS THEN
            CALL cl_err('foreach:',STATUS,1)
            EXIT FOREACH
        END IF
        LET g_cnt = g_cnt + 1
        IF g_cnt > g_max_rec THEN
            CALL cl_err('','9035',0)
            EXIT FOREACH
        END IF
    END FOREACH

    CALL ${detailTables[0].arrayName}.deleteElement(g_cnt)
    MESSAGE ""
    LET g_rec_b = g_cnt - 1
    DISPLAY g_rec_b TO FORMONLY.cn2
    LET g_cnt = 0

END FUNCTION

################################################################################
# Descriptions...: 数据显示
# Memo...........:
# Usage..........: CALL ${programNameId}_bp(p_ud)
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_bp(p_ud)
DEFINE   p_ud   LIKE type_file.chr1         
 
   IF p_ud <> "G" OR g_action_choice = "detail" THEN
      RETURN
   END IF
 
   LET g_action_choice = " "
 
   CALL cl_set_act_visible("accept,cancel", FALSE)
   DISPLAY ARRAY ${detailTables[0].arrayName} TO ${formData.formName}.* ATTRIBUTE(COUNT=g_rec_b,UNBUFFERED)
 
   BEFORE DISPLAY
      CALL cl_navigator_setting( g_curs_index, g_row_count )
 
      BEFORE ROW
      LET l_ac = ARR_CURR()
      CALL cl_show_fld_cont()                  
 
      ON ACTION insert
         LET g_action_choice="insert"
         EXIT DISPLAY

      ON ACTION query
         LET g_action_choice="query"
         EXIT DISPLAY

      ON ACTION delete
         LET g_action_choice="delete"
         EXIT DISPLAY

      ON ACTION first 
         CALL ${programNameId}_fetch('F')
         CALL cl_navigator_setting(g_curs_index, g_row_count)   
         IF g_rec_b != 0 THEN
            CALL fgl_set_arr_curr(1)  
         END IF
      ACCEPT DISPLAY                   
      
      ON ACTION previous
         CALL ${programNameId}_fetch('P')
         CALL cl_navigator_setting(g_curs_index, g_row_count)   
         IF g_rec_b != 0 THEN
            CALL fgl_set_arr_curr(1)  
         END IF
      ACCEPT DISPLAY                   

      ON ACTION jump 
         CALL ${programNameId}_fetch('/')
         CALL cl_navigator_setting(g_curs_index, g_row_count)   
         IF g_rec_b != 0 THEN
            CALL fgl_set_arr_curr(1)  
         END IF
	   ACCEPT DISPLAY                 
                              
      ON ACTION next
         CALL ${programNameId}_fetch('N')
         CALL cl_navigator_setting(g_curs_index, g_row_count) 
         IF g_rec_b != 0 THEN
            CALL fgl_set_arr_curr(1)  
         END IF
	   ACCEPT DISPLAY                  
                              
      ON ACTION last 
         CALL ${programNameId}_fetch('L')
         CALL cl_navigator_setting(g_curs_index, g_row_count)   
         IF g_rec_b != 0 THEN
            CALL fgl_set_arr_curr(1)  
         END IF
      ACCEPT DISPLAY                   
                              
      ON ACTION detail
         LET g_action_choice="detail"
         LET l_ac = 1
         EXIT DISPLAY

      ON ACTION help
         LET g_action_choice="help"
         EXIT DISPLAY
 
      ON ACTION locale
         CALL cl_dynamic_locale()
         CALL cl_show_fld_cont()                
      
      ON ACTION exit
         LET g_action_choice="exit"
         EXIT DISPLAY

      ON ACTION controlg 
         LET g_action_choice="controlg"
         EXIT DISPLAY
 
      ON ACTION controls                                                                                      
         CALL cl_set_head_visible("","AUTO")      
 
      ON ACTION accept
         LET g_action_choice="detail"
         LET l_ac = ARR_CURR()
         EXIT DISPLAY

      ON ACTION cancel
         LET INT_FLAG=FALSE 	
         LET g_action_choice="exit"
         EXIT DISPLAY
 
      ON IDLE g_idle_seconds
         CALL cl_on_idle()
         CONTINUE DISPLAY
 
      ON ACTION about        
         CALL cl_about()     
   
      ON ACTION exporttoexcel      
         LET g_action_choice = 'exporttoexcel'
         EXIT DISPLAY
 
      AFTER DISPLAY
         CONTINUE DISPLAY

   END DISPLAY
   CALL cl_set_act_visible("accept,cancel", TRUE)
 
END FUNCTION

################################################################################
# Descriptions...: 删除数据
# Memo...........:
# Usage..........: CALL ${programNameId}_r()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${formData.author}
# Modify.........:
################################################################################
FUNCTION ${programNameId}_r()
DEFINE l_chr,l_sure LIKE type_file.chr1      
 
    IF s_shut(0) THEN RETURN END IF
    IF ${masterTable.arrayName}.${masterPkFields[0]} IS NULL THEN CALL cl_err('',-400,0) RETURN END IF
 
    BEGIN WORK
 
    OPEN ${programNameId}_cl USING ${masterPkFields
        .map(field => `${masterTable.arrayName}.${field}`)
        .join(',')}

    IF SQLCA.sqlcode THEN 
       CALL cl_err(${masterTable.arrayName}.${masterPkFields[0]},SQLCA.sqlcode,0)
       CLOSE ${programNameId}_cl ROLLBACK WORK RETURN 
    END IF
 
    FETCH ${programNameId}_cl INTO ${masterTable.arrayName}.*
    IF SQLCA.sqlcode THEN 
       CALL cl_err(${masterTable.arrayName}.${masterPkFields[0]},SQLCA.sqlcode,0)
       CLOSE ${programNameId}_cl ROLLBACK WORK RETURN 
    END IF
 
    CALL ${programNameId}_show()
 
    IF cl_delh(20,16) THEN                           
        DELETE FROM ${detailTables[0].insertTable} 
         WHERE ${masterPkFields
            .map(field => `${field} = ${masterTable.arrayName}.${field}`)  
            .join(' AND ')}

        IF SQLCA.SQLERRD[3]=0 THEN
           CALL cl_err3("del","${masterTable.insertTable}",${masterTable.arrayName}.${masterPkFields[0]},"",SQLCA.sqlcode,"","",1)  #No.FUN-660167
        ELSE
         
           CLEAR FORM
           CALL ${detailTables[0].arrayName}.clear()
           
    	   INITIALIZE ${masterTable.arrayName}.* TO NULL            
           OPEN ${programNameId}_count
           IF STATUS THEN
              CLOSE ${programNameId}_cs
              CLOSE ${programNameId}_count
              COMMIT WORK
              RETURN
           END IF

           FETCH ${programNameId}_count INTO g_row_count
           IF STATUS OR (cl_null(g_row_count) OR  g_row_count = 0 ) THEN
              CLOSE ${programNameId}_cs
              CLOSE ${programNameId}_count
              COMMIT WORK
              RETURN
           END IF

           DISPLAY g_row_count TO FORMONLY.cnt

           OPEN ${programNameId}_cs
           IF g_curs_index = g_row_count + 1 THEN
              LET g_jump = g_row_count
              CALL ${programNameId}_fetch('L')
           ELSE
              LET g_jump = g_curs_index
              LET mi_no_ask = TRUE
              CALL ${programNameId}_fetch('/')
           END IF
        END IF
    END IF
 
    CLOSE ${programNameId}_cl
    COMMIT WORK
    
END FUNCTION

`;

    return code;
  };

  return {
    generateFakeDoubleCode,
    generatedCode
  };
}